package com.utils.json;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import javafx.event.Event;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;


import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class JsonUtils {
    private static ObjectMapper mapper = new ObjectMapper();
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    static {
        mapper.setDateFormat(sdf);
    }

    /**
     * 传入一个Bean对象转化为json并输出
     * @param outputStream 字节流
     * @param object 对象
     */
    public static void write(OutputStream outputStream, Object object) {
        // 转换工具
        try {
            // 将对象转换成json语句并输出
            mapper.writeValue(outputStream, object);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("转json输出失败！", e);
        }
    }

    /**
     * 将Bean对象转换为json字符串
     *
     * @param object 对象
     * @return String
     */
    public static String getJsonString(Object object) {
        // 转换工具
        try {
            // 将对象转换成json语句并输出
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("转json失败！", e);
        }
    }
    private static ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 把json数组转为Bean对象
     *
     * @param json json语句
     * @return 返回一个泛型对象
     */
    public static <T> T readValue(String json, Class<? extends T> clazz) {
        T bean = null;
        try {
            bean = objectMapper.readValue(json,clazz);
        } catch (Exception e) {
            System.out.println("json转对象失败！");
            System.out.println(e.getMessage());
        }
        return bean;
    }

    public static void main(String[] args) throws IOException {
        String json = "{name:'party',eventDate:'20-12-2014 02:30:00'}";
        SimpleDateFormat df= new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(df);
        Event event = mapper.readerFor(Event.class).readValue(json);
        System.out.println(event);
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.setDateFormat(df);
//     
//        Event event = mapper.readerFor(Event.class).readValue(json);
//        assertEquals("20-12-2014 02:30:00", df.format(event.eventDate));
    }
}
